const { STATUS_CODE } = require('../../../constants');
const dbService = require('../../../service/dbService');

const validateMomentAuth = async (ctx, next) => {
  const { url } = ctx.request;
  let { id: momentId } = ctx.request.body;
  if (url.includes('delete')) {
    momentId = ctx.params.id;
  }
  const userId = ctx.user.id;
  const result = await dbService.query({ id: momentId, user_id: userId }, 'moment');
  if (result[0]) {
    await next();
  } else {
    ctx.app.emit('error', new Error(STATUS_CODE.FORBIDDEN), ctx);
    return;
  }
};

module.exports = validateMomentAuth;
